/**
链接：https://leetcode-cn.com/problems/binary-tree-level-order-traversal

二叉树：[3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果：

[
  [3],
  [9,20],
  [15,7]
]
*/

/**
    - 1、queue.push(root)
    - 2、for循环
        - node = queue.pop
        - queue.push node->left（栈底，出栈时【慢】访问）
        - queue.push node->right（栈顶，出栈时【先】访问）
*/

class Solution {
public:
    levelOrder(TreeNode* root)
    {
        if (!root) return nullptr;

        vector <vector <int>> vec;

        queue <TreeNode*> q;
        q.push(root);

        while (!q.empty())
        {
            vec.push_back(vector <int> ());

            int currentLevelSize = q.size();
            for (int i = 1; i <= currentLevelSize; ++i) // 控制出队的次数
            {
                auto node = q.front();
                q.pop();

                vec.back().push_back(node->val);

                if (node->left) q.push(node->left);

                if (node->right) q.push(node->right);
            }
        }

        return vec;
    }
};
